package cn.zhikaizhang.indexviewdemo.demo2;

import android.app.Activity;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.widget.ListView;
import cn.zhikaizhang.indexview.Binder;
import cn.zhikaizhang.indexview.IndexView;
import cn.zhikaizhang.indexview.PinyinComparator;
import cn.zhikaizhang.indexviewdemo.R;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Demo2 extends Activity {

  private ListView listView;
  private IndexView indexView;
  private List<Item> list = new ArrayList<>();
  private AsyncQueryHandler asyncQuery;
  private MyAdapter mAdapter;

  @Override protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.demo2);
    asyncQuery = new MyAsyncQueryHandler(getContentResolver());
    //List<Item> items = getData();
    //Collections.sort(items, new PinyinComparator<Item>() {
    //    @Override
    //    public int compare(Item s1, Item s2) {
    //        return compare(s1.getUserName(), s2.getUserName());
    //    }
    //});
    //
    listView = (ListView) findViewById(R.id.listview);
    mAdapter = new MyAdapter(this);
    listView.setAdapter(mAdapter);

    indexView = (IndexView) findViewById(R.id.indexView);
    //init();
    printContacts();
  }

  private void init() {
    Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI; // 联系人的Uri
    String[] projection = {
        ContactsContract.CommonDataKinds.Phone._ID,
        ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
        ContactsContract.CommonDataKinds.Phone.DATA1, "sort_key",
        ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
        ContactsContract.CommonDataKinds.Phone.PHOTO_ID,
        ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY
    }; // 查询的列
    asyncQuery.startQuery(0, null, uri, projection, null, null,
        "sort_key COLLATE LOCALIZED asc"); // 按照sort_key升序查询
  }

  private void setData() {
    Collections.sort(list, new PinyinComparator<Item>() {
      @Override public int compare(Item s1, Item s2) {
        return compare(s1.getUserName(), s2.getUserName());
      }
    });
    mAdapter.setData(list);
    Binder binder = new Binder(listView, indexView) {
      @Override public String getListItemKey(int position) {
        return ((Item) (listView.getAdapter().getItem(position))).getUserName();
      }
    };
    binder.bind();
    //listView = (ListView)findViewById(R.id.listview);
    //listView.setAdapter(new MyAdapter(this, list));
    //
    //indexView = (IndexView) findViewById(R.id.indexView);
    //
    //Binder binder = new Binder(listView, indexView) {
    //    @Override
    //    public String getListItemKey(int position) {
    //        return ((Item)(listView.getAdapter().getItem(position))).getUserName();
    //    }
    //};
    //binder.bind();
  }

  /*
    * 自定义显示Contacts提供的联系人的方法
    */
  public void printContacts() {
    ContentResolver contentResolver = getContentResolver();

    // 这里只查询指定的列
    String[] projection = {
        ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts._ID,
        ContactsContract.Contacts.HAS_PHONE_NUMBER, ContactsContract.Contacts.SORT_KEY_PRIMARY,
    };

    // Uri.parse("content://com.android.contacts/contacts"
    // 获得所有的联系人, 按照sort_key升序查询
    Cursor cursor =
        contentResolver.query(ContactsContract.Contacts.CONTENT_URI, projection, null, null,
            "sort_key COLLATE LOCALIZED asc");

    // 循环遍历
    if (cursor != null && cursor.moveToFirst()) {
      int idColumn = cursor.getColumnIndex(ContactsContract.Contacts._ID);
      int displayNameColumn = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);

      do {
        // 获得联系人的ID
        String contactId = cursor.getString(idColumn);
        // 获得联系人姓名
        String displayName = cursor.getString(displayNameColumn);

        // 查看联系人有多少个号码，如果没有号码，返回0
        int phoneCount =
            cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

        if (phoneCount > 0) {
          // 获得联系人的电话号码列表
          Cursor phoneCursor =
              getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                  ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId, null, null);
          if (cursor != null && phoneCursor.moveToFirst()) {
            do {
              //遍历所有的联系人下面所有的电话号码
              String phoneNumber = phoneCursor.getString(
                  phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
              Log.i("fcy", "----------------- num=" + phoneNumber);
            } while (phoneCursor.moveToNext());
          }
        }
      } while (cursor.moveToNext());
    }
  }

  /**
   * 数据库异步查询类AsyncQueryHandler
   *
   * @author administrator
   */
  private class MyAsyncQueryHandler extends AsyncQueryHandler {

    public MyAsyncQueryHandler(ContentResolver cr) {
      super(cr);
    }

    /**
     * 查询结束的回调函数
     */
    @Override protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
      if (cursor != null && cursor.getCount() > 0) {

        cursor.moveToFirst();
        for (int i = 0; i < cursor.getCount(); i++) {
          cursor.moveToPosition(i);
          String name = cursor.getString(1);
          String number = cursor.getString(2);
          String sortKey = cursor.getString(3);
          int contactId = cursor.getInt(4);
          Long photoId = cursor.getLong(5);
          String lookUpKey = cursor.getString(6);
          list.add(new Item(name, number));

          //if (contactIdMap.containsKey(contactId)) {
          //
          //} else {
          //
          //    ContactBean cb = new ContactBean();
          //    cb.setDisplayName(name);
          //    //					if (number.startsWith("+86")) {// 去除多余的中国地区号码标志，对这个程序没有影响。
          //    //						cb.setPhoneNum(number.substring(3));
          //    //					} else {
          //    cb.setPhoneNum(number);
          //    //					}
          //    cb.setSortKey(sortKey);
          //    cb.setContactId(contactId);
          //    cb.setPhotoId(photoId);
          //    cb.setLookUpKey(lookUpKey);
          //    list.add(cb);
          //
          //    contactIdMap.put(contactId, cb);
          //
          //}
        }
        if (list.size() > 0) {
          //setAdapter(list);
          setData();
        }
      }
    }
  }

  private List<Item> getData() {

    List<Item> items = new ArrayList<>();
    items.add(new Item("路平"));
    items.add(new Item("苏唐"));
    items.add(new Item("莫林"));
    items.add(new Item("燕西凡"));
    items.add(new Item("郭有道"));
    items.add(new Item("楚敏"));
    items.add(new Item("123"));
    items.add(new Item("秦桑"));
    items.add(new Item("秦琪"));
    items.add(new Item("a炳"));
    items.add(new Item("燕秋辞"));
    items.add(new Item("昭音初"));
    items.add(new Item("吕沉风"));
    items.add(new Item("林天表"));
    items.add(new Item("方倚注"));
    items.add(new Item("唐小妹"));
    items.add(new Item("孙迎升"));
    items.add(new Item("孙送招"));
    items.add(new Item("查梦良"));
    items.add(new Item("秦越"));
    items.add(new Item("严歌"));
    items.add(new Item("徐迈"));
    items.add(new Item("詹仁"));
    items.add(new Item("许唯风"));
    items.add(new Item("宋远"));
    items.add(new Item("李遥天"));
    items.add(new Item("陈楚"));
    items.add(new Item("霍英"));
    items.add(new Item("程落烛"));
    items.add(new Item("郭无术"));
    items.add(new Item("阮青竹"));
    items.add(new Item("严鸣"));
    return items;
  }
}
